/**
 * Copyright (c) 2018-2028, Joffee.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sailmi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sailmi.common.controller.BaseController;
import com.sailmi.common.constant.RoleConstant;
import com.sailmi.common.model.auth.AuthInfo;
import com.sailmi.common.mybatis.support.Condition;
import com.sailmi.common.secure.annotion.PreAuth;
import com.sailmi.common.tool.api.R;
import com.sailmi.common.tool.support.Kv;
import com.sailmi.common.tool.utils.Func;
import com.sailmi.common.tool.utils.SecureUtil;
import com.sailmi.system.entity.SystemEntity;
import com.sailmi.system.service.ISystemService;
import io.swagger.v3.oas.annotations.Operation;
import com.sailmi.system.entity.Menu;
import com.sailmi.system.service.IMenuService;
import com.sailmi.system.vo.MenuVO;
import com.sailmi.system.wrapper.MenuWrapper;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 控制器
 *
 * @author Joffee
 */
@RestController
@RequestMapping("/menu")
@Tag(name = "菜单", description = "菜单管理接口")
public class MenuController extends BaseController {

	private final IMenuService menuService;
	private final ISystemService systemService;

	public MenuController(IMenuService menuService, ISystemService systemService) {
		this.menuService = menuService;
		this.systemService = systemService;
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@Operation(summary = "详情", description = "传入menu")
	public R<MenuVO> detail(Menu menu) {
		Menu detail = menuService.getOne(Condition.getQueryWrapper(menu));
		return R.data(MenuWrapper.build().entityVO(detail));
	}

	/**
	 * 列表
	 */
	@GetMapping("/list")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@Operation(summary = "列表", description = "传入menu")
	public R<List<MenuVO>> list(@RequestParam @ModelAttribute Map<String, Object> menu,HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		ArrayList<Long> systemIds = new ArrayList<>();
		if(authInfo!=null && authInfo.getTenantId()!=null ){
			QueryWrapper<SystemEntity> systemEntityQueryWrapper = new QueryWrapper<>();
			if(authInfo.getTenantId().equals("000000")){//平台管理员
				//可以看到租户管理的菜单
			}else{
				systemEntityQueryWrapper.eq("tenant_id",authInfo.getTenantId());
			}

			List<SystemEntity> list = systemService.list(systemEntityQueryWrapper);
			if(list!=null && list.size()>0){
				list.stream().forEach(sysEntity->{
					systemIds.add(sysEntity.getId());
				});
			}
		}
		QueryWrapper<Menu> queryWrapper = Condition.getQueryWrapper(menu, Menu.class);
		if(systemIds!=null && systemIds.size()>0){
			queryWrapper.in("system_id",systemIds);
		}
		@SuppressWarnings("unchecked")
		List<Menu> list = menuService.list(queryWrapper.lambda().orderByAsc(Menu::getSort));
		List<MenuVO> menuVOS = MenuWrapper.build().listNodeVO(list);
		if(menuVOS!=null && menuVOS.size()>0){
			menuVOS.stream().forEach(menuVO->{
				menuVO.setSystemName(systemService.getById(menuVO.getSystemId()).getSystemName());
			});
		}
		return R.data(menuVOS);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@Operation(summary = "新增或修改", description = "传入menu")
	public R submit(@Valid @RequestBody Menu menu) {
		return R.status(menuService.saveOrUpdate(menu));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	@Operation(summary = "删除", description = "传入ids")
	public R remove(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		return R.status(menuService.removeByIds(Func.toLongList(ids)));
	}


	@PostMapping("/serviceMenus")
	@Operation(summary = "菜单列表", description = "传入enterpriseid")
	public R<List<MenuVO>> queryEnterpriseServiceMenus(String enterpriseId){


		return  null;
	}


	/**
	 * 前端菜单数据
	 */
	@GetMapping("/routes")
	@Operation(summary = "前端菜单数据", description = "前端菜单数据")
	public R<List<MenuVO>> routes(@RequestParam(name="consoleType",required = false) Long consoleType) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		List<MenuVO> list = new ArrayList<>();
		System.out.println("Console Type is:"+consoleType);
		System.out.println("Authority Info is:"+authInfo.getAuthority());
		if(Objects.nonNull(consoleType)){
			list = menuService.routes(consoleType.intValue(),authInfo.getAuthority());
		}else{
			list = menuService.routes(authInfo.getAuthority());
		}
		return R.data(list);
	}

	/**
	 * 前端按钮数据
	 */
	@GetMapping("/buttons")
	@Operation(summary = "前端按钮数据", description = "前端按钮数据")
	public R<List<MenuVO>> buttons() {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		List<MenuVO> list = menuService.buttons(authInfo.getAuthority());
		return R.data(list);
	}

	/**
	 * 获取菜单树形结构
	 */
	@GetMapping("/tree")
	@Operation(summary = "功能树", description = "功能树")
	public R<List<MenuVO>> tree() {
		List<MenuVO> tree = menuService.tree();
		return R.data(tree);
	}

	/**
	 * 根据角色类型，获取菜单树形结构
	 */
	@GetMapping("/tree_roletype")
	@Operation(summary = "功能树", description = "功能树")
	public R<List<MenuVO>> treeByRoleType(@RequestParam(name="roletype") int roletype) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		List<String> roleList = Func.toStrList(authInfo.getAuthority());
		if(roleList.contains(String.valueOf(roletype))){
			List<MenuVO> tree = menuService.tree();
			return R.data(tree);
		}else{
			return R.fail("用户无此类权限");
		}
	}


	/**
	 * 获取权限分配树形结构
	 */
	@GetMapping("/grant-tree")
	@Operation(summary = "权限分配树形结构", description = "权限分配树形结构")
	public R<List<MenuVO>> grantTree(HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		return R.data(menuService.grantTree(authInfo));
	}


	/**
	 * 服务包菜单分配树形结构
	 */
	@GetMapping("/grantservicemenu-tree")
	@Operation(summary = "权限分配树形结构", description = "权限分配树形结构")
	public R<List<MenuVO>> grantServiceTree(HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		return R.data(menuService.grantServiceMenuTree(authInfo.getTenantId()));
	}

	/**
	 * 获取权限分配树形结构
	 */
	@GetMapping("/role-tree-keys")
	@Operation(summary = "角色所分配的树", description = "角色所分配的树")
	public R<List<String>> roleTreeKeys(@RequestParam(name="roleIds") String roleIds) {
		return R.data(menuService.roleTreeKeys(roleIds));
	}

	/**
	 * 获取配置的角色权限
	 */
	@GetMapping("auth-routes")
	@Operation(summary = "菜单的角色权限")
	public R<List<Kv>> authRoutes(HttpServletRequest request) {
		AuthInfo authInfo = SecureUtil.getAuthInfo();
		return R.data(menuService.authRoutes(authInfo.getAuthUser()));
	}

}
